package Conprehersive;

public class Test {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        productor p = new productor(clerk);
        consumer p1 = new consumer(clerk);
        consumer c = new consumer(clerk);
        p.setName("生产者1");
        p1.setName("消费者2");
        c.setName("消费者1");
        p.start();
        p1.start();
        c.start();
    }
}

class Clerk {
    private int production=0;
    public synchronized void producer() {
        if (production < 20) {
            production++;
            System.out.println(Thread.currentThread().getName() + ":开始生产第" + production + "个产品");
            notify();
        } else {
            System.out.println("请停止生产！！");
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void Serve() {
        if (production > 0) {
            production--;
            System.out.println(Thread.currentThread().getName() + ":取走第" + (production + 1) + "个产品");
            notify();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class productor extends Thread {
    private Clerk clerk;
    public productor(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while (true) {
            System.out.println("开始生产~~~~~~");
            try {
                sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.producer();
        }
    }
}

class consumer extends Thread {
    private Clerk clerk;

    public consumer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        System.out.println("开始消费~~~~~");

        while (true) {
            try {
                sleep(21);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
                clerk.Serve();
        }
    }
}